﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public abstract class Spline : MonoBehaviour {
	
	public List<Vector3> controlPoints = new List<Vector3>();
	public int curveCount { get { return controlPoints != null ? (controlPoints.Count - 1) / 3 : 0; } }
	protected float percentagePerSection { get { return 1f / curveCount; } } 
	public const int divisionsPerCurve = 30;

	public abstract Vector3 GetPointInCurve(float t,
		Vector3 point0, Vector3 point1, Vector3 point2, Vector3 point3);



	public List<Vector3> WorldToLocalPoints(List<Vector3> worldPoints){
		List<Vector3> localPoints = new List<Vector3>();
		for(int i = 0; i < worldPoints.Count; i++){
			localPoints.Add(transform.TransformPoint(worldPoints[i]) );
		}
		return localPoints;
	}

	public List<Vector3> LocalToWorldPoints(List<Vector3> localPoints){
		List<Vector3> worldPoints = new List<Vector3>();
		for(int i = 0; i < localPoints.Count; i++){
			worldPoints.Add(transform.InverseTransformPoint(localPoints[i]) );
		}
		return worldPoints;
	}

	public List<Vector3> GetDrawingPoints(){
		List<Vector3> drawingPoints = new List<Vector3>();
		List<Vector3> localPoints = WorldToLocalPoints(controlPoints);
		for(int i = 0; i < localPoints.Count - 3; i+= 3){
			Vector3 p0 = localPoints[i];
			Vector3 p1 = localPoints[i + 1];
			Vector3 p2 = localPoints[i + 2];
			Vector3 p3 = localPoints[i + 3];

			if(i == 0){
				drawingPoints.Add(GetPointInCurve(0f, p0,p1,p2,p3));
			}

			for(int j = 1; j <= divisionsPerCurve; j++){
				float t = j / (float) divisionsPerCurve;
				drawingPoints.Add(GetPointInCurve(t, p0, p1, p2, p3));
			}
		}
		return drawingPoints;
	}
}
